package org.example.web;

import org.example.vo.LoginProperties;
import org.example.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/6/4
 * Email haijunzhou@hnit.edu.cn
 */
@RestController
@RequestMapping("lg")
public class LoginDo {

    @Autowired
    LoginProperties loginProperties;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @RequestMapping("login")
    Result login(String name, String pwd, HttpSession session,
                 @RequestParam(defaultValue = "no") String autoLogin, HttpServletResponse response)
            throws NoSuchFieldException {
        if(name == null|| name.isBlank()){
            return Result.fail("请输入用户名!");
        }
        if(pwd == null|| pwd.isBlank()){
            return Result.fail("请输入密码!");
        }
        // TODO 自行扩展其他的验证
        String sql = "select * from %s where %s=? and %s=?";
        sql = String.format(sql, loginProperties.getUserTable(),
                loginProperties.getNameColumn(),
                loginProperties.getPwdColumn());

        // 我们的解决方案: 将用户名和密码连接=>再编码成md5
        if("md5".equalsIgnoreCase(loginProperties.getEncryption())){
            String md5 = DigestUtils.md5DigestAsHex((name + pwd).getBytes(StandardCharsets.UTF_8));
            pwd = md5;
        }

        try{
            // BeanPropertyRowMapper
            Object user = jdbcTemplate.queryForObject(sql,
                    new BeanPropertyRowMapper<>(loginProperties.getUserClassObject()),
                    name, pwd);
            session.setAttribute(loginProperties.getSessionKey(),user);

            /*// 自动登录
            if(Boolean.TRUE.equals(autologin)){
                Field field = user.getClass().getDeclaredField("id");
                field.setAccessible(true);
                Object id = field.get(user);
                Cookie cookie = new Cookie("KLGHLJNHL", id+"");
                // 有效期 1 周, 单位:秒
                cookie.setMaxAge( 24*7*60*60 );
                cookie.setPath("/");
                // 将用户id发送到浏览器
                response.addCookie(cookie);
            }*/
            switch(autoLogin){
                case "no":
                    System.out.println("autoLogin = " + autoLogin);
                    setAutoLogin(response,0,user);
                    setAutoLoginTime(response,autoLogin,0);
                    break;
                case "day":
                    System.out.println("autoLogin = " + autoLogin);
                    setAutoLogin(response,(24*60*60),user);
                    setAutoLoginTime(response,autoLogin,(24*60*60));
                    break;
                case "week":
                    System.out.println("autoLogin = " + autoLogin);
                    setAutoLogin(response,(7*24*60*60),user);
                    setAutoLoginTime(response,autoLogin,(7*24*60*60));
                    break;
                case "month":
                    System.out.println("autoLogin = " + autoLogin);
                    setAutoLogin(response,(31*24*60*60),user);
                    setAutoLoginTime(response,autoLogin,(31*24*60*60));
                    break;
            }
            return Result.ok("登录成功!", user);
        }catch (DataAccessException e){
            e.printStackTrace();
            return Result.fail("用户名或密码错误!");
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public void setAutoLogin(HttpServletResponse response,int time,Object user) throws NoSuchFieldException, IllegalAccessException {
        Field idField = user.getClass().getDeclaredField("id");
        idField.setAccessible(true);//设置强制访问
        Object id = idField.get(user);//在通过对象来获取对象里面id的值
        //将用户的id存到cookie里面去
        Cookie cookie=new Cookie("KLGHLJNHL",id+"");
        //设置有效期为一周   单位为s   如果不设置有效期的话  关闭浏览器就没有了
        cookie.setMaxAge(time);
        cookie.setPath("/");
        response.addCookie(cookie);

    }
    public void setAutoLoginTime(HttpServletResponse response,String timeType,int time) throws NoSuchFieldException, IllegalAccessException {

        //将用户的id存到cookie里面去
        Cookie cookie=new Cookie("UIANT",timeType);
        //设置有效期为一周   单位为s   如果不设置有效期的话  关闭浏览器就没有了
        cookie.setMaxAge(time);
        cookie.setPath("/");
        response.addCookie(cookie);

    }
    @GetMapping("myinfo")
    Result getLoginedUser(HttpSession session){
        Object user = session.getAttribute(loginProperties.getSessionKey());
        if(user==null){
            return Result.fail("未登录!");
        } else {
            return Result.ok("已登录", user);
        }
    }

    @GetMapping("logout")
    ModelAndView logout(HttpSession session,
                        HttpServletResponse response,
                        ModelAndView modelAndView){
        session.invalidate();

        // 移除
        Cookie cookie = new Cookie("KLGHLJNHL", "");
        // 有效期 1 周, 单位:秒
        cookie.setMaxAge( 0 );
        cookie.setPath("/");
        // 将用户id发送到浏览器
        response.addCookie(cookie);

        modelAndView.setViewName("redirect:/index.html");
        return modelAndView;
    }

    @RequestMapping("upPwd")
    public Result upPwd(String user, String oldPwd, String newPwd, HttpSession session,
                        HttpServletRequest request,
                        HttpServletResponse response) throws IOException {


        String rvcode = request.getParameter("vcode");
        String svcode = (String)request.getSession().getAttribute("vcode");
        Result result;
        if(rvcode == null || rvcode.isBlank()){
            //String json = objectMapper.writeValueAsString(request);
            result = new Result(0,"请输入验证码",null);
           /* response.setContentType("application/json;charset=utf-8");
            response.getWriter().append(json);*/
            return result;
        }else if(rvcode.equalsIgnoreCase(svcode)==false){
            result = new Result(0,"验证码输入错误",null);
            /* out(result,response);*/
            return result;
        }

        System.out.println(user+"+++"+newPwd+"++"+oldPwd);
        System.out.println(session.getAttribute(loginProperties.getSessionKey()).toString());
        String sql = "update %s set %s=? where %s=? and %s=?";
        sql = String.format(sql, loginProperties.getUserTable(),
                loginProperties.getPwdColumn(),
                loginProperties.getPwdColumn(),
                loginProperties.getNameColumn());

        if ("md5".equalsIgnoreCase(loginProperties.getEncryption())) {
            String md5 = DigestUtils.md5DigestAsHex((user + newPwd).getBytes(StandardCharsets.UTF_8));
            String md5b = DigestUtils.md5DigestAsHex((user + oldPwd).getBytes(StandardCharsets.UTF_8));
            newPwd = md5;
            oldPwd = md5b;
            System.out.println(newPwd);
            System.out.println(oldPwd);
        }
        System.out.println(sql);
        int res = jdbcTemplate.update(sql, newPwd,oldPwd, user);

        if (res <= 0) {
            return Result.fail("密码修改失败");
        } else {
            session.invalidate();
            return Result.ok("密码修改成功");
        }

    }

}
